%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%% @end
%%%-------------------------------------------------------------------
-module(gate_svr).

-behaviour(gen_server).

-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
    code_change/3, start_gate_svr/0]).

-include("obj.hrl").

-define(SVR_PORT, 65500).
-define(SERVER, ?MODULE).

-record(state, {lsock, sock}).

%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_gate_svr() ->
    ChildSpec = #{id => ?MODULE,
        start => {?MODULE, start_link, []},
        restart => permanent,
        shutdown => 2000,
        type => worker,
        modules => [?MODULE]},
    supervisor:start_child(tower_aoi_server_sup, ChildSpec).

start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

init([]) ->
    {ok, LSock} = gen_tcp:listen(?SVR_PORT, [{keepalive, true}, {mode, binary}]),
    self() ! start_accept,
    {ok, #state{lsock = LSock}}.

handle_call(_Request, _From, State = #state{}) ->
    {reply, ok, State}.

handle_cast(_Request, State = #state{}) ->
    {noreply, State}.

handle_info(start_accept, State) ->
    accept(State);

handle_info({inet_async, LSock, _Ref, {ok, Sock}}, State = #state{lsock = LSock}) ->
    gate_recv_svr:start_recv_svr(Sock),
    io:format("Sock ~p Connect~n", [Sock]),
    accept(State);

handle_info(_Info, State = #state{}) ->
    {noreply, State}.

terminate(_Reason, _State = #state{}) ->
    ok.

code_change(_OldVsn, State = #state{}, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

accept(State = #state{lsock = LSock}) ->
    case prim_inet:async_accept(LSock, -1) of
        {ok, _} ->
            ok;
        _ ->
            pass
    end,
    {noreply, State}.



